import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

typedef DialogOptionBuilder<T> = Map<String, T> Function();

Future<T?> showGenericDialog<T>({
  required BuildContext context,
  required String title,
  required String content,
  required DialogOptionBuilder optionsBuilder,
}) {
  final options = optionsBuilder();
  return showDialog<T>(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: options.keys.map(
          (optionTitle) {
            final T value = options[optionTitle];
            return TextButton(
              onPressed: () async {
                // 触觉反馈
                await HapticFeedback.lightImpact();
                Navigator.of(context).pop(value);
              },
              child: Text(optionTitle),
            );
          },
        ).toList(),
      );
    },
  );
}

Future<bool> showLogOutDialog(BuildContext context) {
  return showGenericDialog<bool>(
    context: context,
    title: 'Log out',
    content: 'Are you sure you want to log out?',
    optionsBuilder: () => {
      '取消': false,
      '确认': true,
    },
  ).then(
    (value) => value ?? false,
  );
}

class GenericDialogPage extends StatelessWidget {
  GenericDialogPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Generic Dialog"),
      ),
      body: SafeArea(
        child: Center(
          child: TextButton(
            onPressed: () {
              showLogOutDialog(context).then((value) => print(value));
            },
            child: Text('Dialog'),
          ),
        ),
      ),
    );
  }
}
